package com.ruike.alisurface.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.ruike.alisurface.services.AppRunMonitoringService.isNeedStop;

/**
 * Author: voodoo
 * CreateDate: 2020-03-27 027 下午 03:51
 * Description:
 */
public class APPUtils {

    /**
     * 判断指定包名的APK是否在运行
     *
     * @param context 上下文
     * @return 是否正在运行
     */
    public static boolean isAppRunning(Context context, String packageNameStr) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageNameStr) && info.baseActivity.getPackageName().equals(packageNameStr)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断指定包名的APK是否在前台运行
     *
     * @param context 上下文
     * @return 是否正在前台运行
     */
    public static boolean isAppRunningForeground(Context context, String packageNameStr) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses) {
            if (info.processName.equals(packageNameStr) && info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将指定包名的app从后台拎回到前台
     *
     * @param context        上下文
     * @param packageNameStr 指定的包名
     */
    public static void setTopApp(Context context, String packageNameStr) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageNameStr) && info.baseActivity.getPackageName().equals(packageNameStr)) {
                activityManager.moveTaskToFront(info.id, 0);
            }
        }
    }

    /**
     * 获取手机内所有应用（包括系统应用）
     *
     * @param context 上下文
     * @return 应用列表
     */
    public static List<PackageInfo> getAllApps(Context context) {
        PackageManager packageManager = context.getPackageManager();
        // 获取手机内所有应用
        return packageManager.getInstalledPackages(0);
    }

    /**
     * 获取手机内安装的第三方应用
     *
     * @param context 上下文
     * @return 应用列表
     */
    public static List<PackageInfo> getThirdPartyApps(Context context) {
        List<PackageInfo> apps = new ArrayList<>();
        List<PackageInfo> packageInfoList = getAllApps(context);
        for (PackageInfo pkgInfo : packageInfoList) {
            // 判断是否为非系统预装应用
            if ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                apps.add(pkgInfo);
            }
        }
        return apps;
    }

    /**
     * 通过包名启动第三方APP
     *
     * @param context     上下文
     * @param packageName 要启动的程序的包名
     * @return 是否启动成功
     */
    public static boolean startOtherApp(Context context, String packageName) {
        boolean isSuccess;
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
            isSuccess = true;
        } catch (Exception e) {
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * 安装APK
     *
     * @param context 上下文
     * @param apkFile 安装包
     */
    public static void installApk(Context context, File apkFile) {

        if (apkFile != null) {   // file 即 apk文件
            isNeedStop = true; // 先把拉起服务停掉
            Intent intent = new Intent(Intent.ACTION_VIEW);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
        }

    }

    /**
     * 卸载APK
     *
     * @param context     上下文
     * @param packageName 需要卸载的包名
     */
    public static void uninstallApk(Context context, String packageName) {
        Uri uri = Uri.fromParts("package", packageName, null);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, uri);
        context.startActivity(uninstallIntent);
    }
    /**
     * 判断指定包名的安装包是否已安装
     *
     * @param context     上下文
     * @param pachageName 包名
     * @return 是否已经安装
     */
    public static boolean isAppInstalled(Context context, String pachageName) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(pachageName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    /**
     * 查询指定包名安装包的路径
     *
     * @param context     上下文
     * @param pachageName 指定的包名，如果为空字符串，则获取当前apk的路径
     * @return 指定包的apk绝对路径
     */
    public static String getApkPath(Context context, String pachageName) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pachageName.isEmpty() ? context.getPackageName() : pachageName, PackageManager.GET_META_DATA);
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            return applicationInfo.sourceDir; // 获取当前apk包的绝对路径
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    /**
     * 获取指定apk的版本号
     *
     * @param context 上下文
     * @param apkPath APK的路径地址
     * @return 版本号，获取不到的话返回-1
     */
    public static int getApkVersionCode(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            return pkgInfo.versionCode; // 得到版本信息
        }
        return -1;
    }

}
